<template>
  <Modal :draggable="!$config.mask"
         :mask="$config.mask"
         :mask-closable="!$config.mask"
         :value="value"
         @on-ok="save"
         @on-visible-change="visibleChange">
    <p slot="header">
      {{ title }}
    </p>
    <Input v-model="filter" clearable icon="md-search" placeholder="输入权限进行筛选" style="width:100%;margin-bottom:10px;"
           @on-enter="handleFilter" @on-click="handleFilter" @on-clear="handleClear"></Input>
    <div class="beautiful-bar" style="max-height: 500px;overflow: auto;">
      <Tree ref="permissionsTree" :check-directly="true" :check-strictly="false" :data="permissions"
            show-checkbox></Tree>
    </div>
    <div v-if="modalData.userId" style="margin-top:10px;">
      <Alert type="warning">如果您正在设置自己的权限，则可能需要刷新页面（F5），以便权限设置生效！</Alert>
    </div>
    <div slot="footer">
      <Button icon="md-finger-print" @click="resetSpecificPermissions" v-if="modalData.userId">重置特殊权限</Button>
      <Button icon="md-close" @click="cancel">取消</Button>
      <Button icon="md-checkmark" type="primary" @click="save">确定</Button>
    </div>
  </Modal>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import Permission from '@/src/store/entities/administration/permission/permission';

@Component({
  components: {},
})

export default class PermissionModal extends AbpBase {
  name: string = 'PermissionModal';

  @Prop({type: Boolean, default: false}) value: boolean;
  @Prop({type: Object}) modalData: any;

  filter: string = '';


  get title() {
    if (this.modalData.userId) {
      return `设置特殊权限：${this.modalData.userName}`;
    }
    return '选择权限';
  }

  get permissions() {
    return this.getTreeData(0, null);
  }


  async save() {
    const checkedNodes = (this.$refs.permissionsTree as any).getCheckedNodes();
    this.$emit('on-confirm', {nodes: checkedNodes, user: this.modalData});
    this.$emit('input', false);
  }

  visibleChange(value: boolean) {
    if (!value) {
      this.reset();
      this.$emit('input', value);
    } else {
      if (this.modalData.userId) {
        this.setSelectedPermissions(this.permissions, this.$store.state.user.permissionForEdit.grantedPermissionNames);
      } else {
        this.setSelectedPermissions(this.permissions, this.modalData.selectedPermissionNames);
      }


      this.handleClear();
    }
  }

  cancel() {
    this.$emit('input', false);
  }

  handleFilter() {
    this.$store.commit('permission/filterPermissions', this.filter);
    if (this.modalData.userId) {
      this.setSelectedPermissions(this.permissions, this.$store.state.user.permissionForEdit.grantedPermissionNames);
    } else {
      this.setSelectedPermissions(this.permissions, this.modalData.selectedPermissionNames);
    }

  }

  handleClear() {
    this.$store.commit('permission/filterPermissions', '');
    if (this.modalData.userId) {
      this.setSelectedPermissions(this.permissions, this.$store.state.user.permissionForEdit.grantedPermissionNames);
    } else {
      this.setSelectedPermissions(this.permissions, this.modalData.selectedPermissionNames);
    }
  }

  async resetSpecificPermissions() {
    this.$M.confirm({
      title: '系统提示',
      content: '确定要重置用户 ' + this.modalData.userName + ' 的特殊权限吗？',
      onOk: async () => {
        await this.$store.dispatch({
          type: 'user/resetUserSpecificPermissions',
          data: {
            id: this.modalData.userId,
          },
        });
        this.$Message.success({
          background: true,
          content: '用户 ' + this.modalData.userName + ' 的特殊权限已成功重置',
          duration: this.$config.duration,
        });
        this.$emit('input', false);
      },
      onCancel: () => {

      },
    });

  }

  getTreeData(level: number, parentName: string) {
    let data: any[] = [];

    const p = this.$store.state.permission.filterPermissions;
    p.forEach((item) => {
      if (item.level === level) {
        if (item.parentName === parentName) {
          let node: any = {};
          node.title = item.displayName;
          node.expand = true;
          node.name = item.name;
          node.children = this.getTreeData(level + 1, item.name);
          data.push(node);
        }
      }
    });
    return data;
  }

  setSelectedPermissions(treeData: any[], selectedPermissionNames: string[]) {
    for (let node of treeData) {
      this.$set(node, 'checked', false);

      this.$set(node, 'indeterminate', false);
      for (let name of selectedPermissionNames) {
        if (name === (node as any).name) {
          this.$set(node, 'checked', true);
          break;
        }
      }
      if ((node as any).children) {
        this.setSelectedPermissions((node as any).children, selectedPermissionNames);
      }
    }
  }

  reset() {
    this.filter = '';
  }



}
</script>

<style lang="less" scoped>

</style>
